package com.zou.lotterylucky.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.view.Window
import android.widget.LinearLayout.VERTICAL
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.jakewharton.rxbinding3.view.clicks
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.v2.request.RequestCenter
import com.v2.utils.TToast
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.R
import com.zou.lotterylucky.adapters.HistoryAdapter
import com.zou.lotterylucky.adapters.RedeemAdapter
import com.zou.lotterylucky.data.RedeemItem
import com.zou.lotterylucky.data.WinningHistory
import com.zou.lotterylucky.utils.DateUtil
import com.zou.lotterylucky.utils.SPUtils
import com.zou.lotterylucky.utils.TLog
import com.zou.lotterylucky.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_setting_inner.*
import kotlinx.android.synthetic.main.activity_setting_inner.searchBtn
import kotlinx.android.synthetic.main.activity_setting_inner.topbar
import kotlinx.android.synthetic.main.activity_win_lotter.*
import kotlinx.android.synthetic.main.winning_history_dialog.*
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class SettingInnerActivity : BaseActivity() {

    private var cal = Calendar.getInstance()
    private lateinit var linearLayoutManager: LinearLayoutManager
    private var redeemList: MutableList<RedeemItem> = mutableListOf()
    private lateinit var adapter: RedeemAdapter

    private lateinit var hLinearLayoutManager: LinearLayoutManager
    private lateinit var hAdapter: HistoryAdapter
    private var winningHistoryList: MutableList<WinningHistory> = mutableListOf()

    private val dateFormatter = SimpleDateFormat("yyyy-MM-dd")

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TLog.v("enter SettingInnerActivity")
        setContentView(R.layout.activity_setting_inner)

        topbar.setTitle(R.string.neibushezhi)
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }

        startDate.text = dateFormatter.format(Date())
        endDate.text = dateFormatter.format(Date())

        val startDateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)

                startDate.text = dateFormatter.format(cal.time)
            }

        val endDateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)

                endDate.text = dateFormatter.format(cal.time)
            }

        startDate.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, startDateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        endDate.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, endDateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        searchBtn.setOnClickListener {
            loadRedeem()
        }

        linearLayoutManager = LinearLayoutManager(this, VERTICAL, false)
        redeemView.layoutManager = linearLayoutManager
        adapter = RedeemAdapter(redeemList, this)
        redeemView.adapter = adapter
        loadRedeem()
    }

    @SuppressLint("WrongConstant", "SimpleDateFormat")
    fun displayDialog(date: String) {
        val requestQueue = Volley.newRequestQueue(this)

//        val url = Constants.SERVER_URL + "getWinningHistoryByDateRange"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
//        params.put("start", date)
//        params.put("end", date)


        RequestCenter.appGetPrizesFromWinningHistory(SPUtils["username", ""] as String, "$date 00:00:00", "$date 23:59:59", object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                val response = JSONObject(result).getJSONObject("data")

                val winningHistory = response.getJSONObject("winningHistories")
                winningHistoryList = mutableListOf()
                winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("K")))
                winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("F")))
                winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("D")))
                winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("S")))

                val dialog = Dialog(this@SettingInnerActivity)
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
                dialog.setCancelable(true)
                dialog.setContentView(R.layout.winning_history_dialog)

                hLinearLayoutManager = LinearLayoutManager(this@SettingInnerActivity, VERTICAL, false)
                dialog.historyView.layoutManager = hLinearLayoutManager
                hAdapter = HistoryAdapter(winningHistoryList)
                dialog.historyView.adapter = hAdapter

                dialog.show()
            }

            override fun onFailure(error: String?) {
                TToast.show("appGetPrizesFromWinningHistory接口失败:$error")
                TLog.net("appGetPrizesFromWinningHistory接口失败:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//
//                    val data = response.get("data") as JSONObject
//                    val winningHistory = data.getJSONObject("winningHistories")
//                    winningHistoryList = mutableListOf()
//                    winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("K")))
//                    winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("F")))
//                    winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("D")))
//                    winningHistoryList.add(WinningHistory(winningHistory.getJSONObject("S")))
//                }
//
//                val dialog = Dialog(this)
//                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
//                dialog.setCancelable(true)
//                dialog.setContentView(R.layout.winning_history_dialog)
//
//                hLinearLayoutManager = LinearLayoutManager(this, VERTICAL, false)
//                dialog.historyView.layoutManager = hLinearLayoutManager
//                hAdapter = HistoryAdapter(winningHistoryList)
//                dialog.historyView.adapter = hAdapter
//
//                dialog.show()
//            } catch (e: JSONException) {
//                e.printStackTrace()
//            }
//        }, { error -> error.printStackTrace() })
//
//        requestQueue?.add(request)
    }

    private fun loadRedeem() {
//        val requestQueue = Volley.newRequestQueue(this)
//
//        val url = Constants.SERVER_URL + "getOrdersByDateRange"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
//        params.put("start", startDate.text.toString())
//        params.put("end", endDate.text.toString())

        RequestCenter.appGetOrdersByDateRange(SPUtils["username", ""] as String, "${startDate.text.toString()} 00:00:00", "${endDate.text.toString()} 23:59:59", object : OkHttpRequestCallback {
            override fun onSuccess(response: String?) {
                val ordersData = JSONObject(response).getJSONArray("data")
                redeemList = mutableListOf()
                for (i in 0 until ordersData.length()) {
                    val redeem = RedeemItem(ordersData.getJSONObject(i))
                    redeemList.add(redeem)
                }

                if (redeemList.size > 0) {
                    sumLayout.visibility = View.VISIBLE
                    sumSalesLbl.text = String.format("%.2f", redeemList.sumByDouble { it.subTotal })
                    sumCommissionLbl.text = String.format("%.2f", redeemList.sumByDouble { it.getCommissionValue() })
                    sumPrizeLbl.text = String.format("%.2f", redeemList.sumByDouble { it.prizes })
                    sumRedemptionLbl.text = String.format("%.2f", redeemList.sumByDouble { it.redeemAmount })
                    sumSettlementLbl.text = String.format("%.2f", redeemList.sumByDouble { it.getSettlement() })
                } else {
                    sumLayout.visibility = View.GONE
                }
                adapter.updateAdapter(redeemList)
            }

            override fun onFailure(error: String?) {
                TLog.net("appGetOrdersByDateRange failure:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.get("data") as JSONObject
//                    val ordersData = data.getJSONArray("orders")
//                    redeemList = mutableListOf()
//                    for (i in 0 until ordersData.length()) {
//                        val redeem = RedeemItem(ordersData.getJSONObject(i))
//                        redeemList.add(redeem)
//                    }
//
//                    if (redeemList.size > 0) {
//                        sumLayout.visibility = View.VISIBLE
//                        sumSalesLbl.text = String.format("%.2f", redeemList.sumByDouble { it.subTotal })
//                        sumCommissionLbl.text = String.format("%.2f", redeemList.sumByDouble { it.getCommissionValue() })
//                        sumPrizeLbl.text = String.format("%.2f", redeemList.sumByDouble { it.prizes })
//                        sumRedemptionLbl.text = String.format("%.2f", redeemList.sumByDouble { it.redeemAmount })
//                        sumSettlementLbl.text = String.format("%.2f", redeemList.sumByDouble { it.getSettlement() })
//                    } else {
//                        sumLayout.visibility = View.GONE
//                    }
//                    adapter.updateAdapter(redeemList)
//                }
//
//            } catch (e: JSONException) {
//                e.printStackTrace()
//            }
//        }, { error -> error.printStackTrace() })
//
//        requestQueue?.add(request)
    }

    private fun changePassword() {
        var editFlag = 0
        var tempPassword = ""
        val builder = QMUIDialog.EditTextDialogBuilder(this)
        val qmuiDialog = builder.setTitle(getString(R.string.shezhimima))
            .setPlaceholder(getString(R.string.qingshurumima))
            .setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            .addAction(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }
            .addAction(R.string.confirm) { dialog, _ ->
                val text = builder.editText.text.toString()
                if (text.isNotEmpty())
                    when (editFlag) {
                        0 -> {
                            val psd =
                                SPUtils.get(
                                    this, Constants.SP_PASSWORD, Constants.default_psd
                                ) as String
                            if (text == psd) {
                                dialog.setTitle(getString(R.string.qingshuruxinmima))
                                builder.editText.setText("")
                                builder.editText.hint = getString(R.string.qingshuruxinmima)
                                editFlag = 1
                            } else {
                                ToastUtil.showMsg(this, getString(R.string.mimacuowu))
                            }
                        }
                        1 -> {
                            tempPassword = text
                            dialog.setTitle(getString(R.string.qingzaicishuruxinmima))
                            builder.editText.setText("")
                            builder.editText.hint = getString(R.string.qingzaicishuruxinmima)
                            editFlag = 2
                        }
                        2 -> {
                            if (tempPassword == text) {
                                SPUtils.set(this, Constants.SP_PASSWORD, tempPassword)
                                dialog.dismiss()
                                ToastUtil.showMsg(this, getString(R.string.shezhimimachenggong))
                            } else {
                                ToastUtil.showMsg(this, getString(R.string.liangcibuyizhi))
                                editFlag = 1
                                dialog.setTitle(R.string.qingshuruxinmima)
                                builder.editText.setText("")
                                builder.editText.hint = getString(R.string.qingshuruxinmima)
                            }
                        }
                    }
            }
            .create()
        qmuiDialog.setCancelable(false)
        qmuiDialog.show()
    }
}
